<?php

namespace App\Http\Controllers\api;

use App\Constant\Enum;
use App\Models\ThirdPartyOrder;
use App\Models\Setting;
use App\Models\User;
use App\Services\Wallet\UserWalletService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class OrderController extends BaseController
{
    /**
     * 接收订单接口
     */
    public function receive(Request $request)
    {
        // 验证UTF-8编码和请求格式
        $this->validateRequestFormat($request);
        
        // 验证请求参数
        $validator = Validator::make($request->all(), [
            'request_id' => 'required|integer',
            'media_id' => 'required|integer', 
            'user_id' => 'required|integer',
            'media_userid' => 'required|string|max:255',
            'type' => 'required|integer',
            'data_id' => 'required|integer',
            'task_id' => 'required|integer',
            'reward' => 'required|string|max:255',
            'media_price' => 'nullable|string|max:255',
            'reward_time' => 'required|integer',
            'remark' => 'nullable|string|max:255',
            'sign' => 'required|string|size:32',
            'project_name' => 'nullable|string|max:255',
            'project_package_name' => 'nullable|string|max:255',
            'project_icon' => 'nullable|string|max:255',
            'task_name' => 'nullable|string|max:255',
            'shop_headimgurl' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 0,
                'message' => '参数错误: ' . $validator->errors()->first()
            ]);
        }

        // 验证签名
        if (!$this->validateSignature($request)) {
            return response()->json([
                'status' => 0,
                'message' => '签名验证失败'
            ]);
        }

        DB::beginTransaction();
        try {
            // 检查是否重复订单
            $existingOrder = ThirdPartyOrder::where('request_id', $request->request_id)
                ->where('media_id', $request->media_id)
                ->first();
            
            if ($existingOrder) {
                return response()->json([
                    'status' => 0,
                    'message' => '订单已存在'
                ]);
            }

            // 根据media_userid查找用户 (media_userid就是我们的UUID)
            $user = User::where('uuid', $request->media_userid)->first();
            if (!$user) {
                return response()->json([
                    'status' => 0,
                    'message' => '用户不存在'
                ]);
            }

            // 获取汇率配置
            $exchangeRate = Setting::get('exchange_rate') ?? 10000;
            
            // 计算奖励金币 (奖励金额是元，需要转换为金币)
            $rewardAmount = floatval($request->reward);
            $rewardCoins = (int)($rewardAmount * $exchangeRate);

            // 创建订单记录
            $orderData = $request->only([
                'request_id', 'media_id', 'user_id', 'media_userid', 'type',
                'data_id', 'task_id', 'reward', 'media_price', 'reward_time',
                'remark', 'sign', 'project_name', 'project_package_name',
                'project_icon', 'task_name', 'shop_headimgurl'
            ]);
            $orderData['reward_coins'] = $rewardCoins;
            $orderData['status'] = 1;
            $orderData['processed_at'] = Carbon::now();

            $order = ThirdPartyOrder::create($orderData);

            // 将奖励金币加入用户钱包 (作为佣金收入)
            if ($rewardCoins > 0) {
                UserWalletService::income($user, $rewardCoins, Enum::WALLET_TYPE_COMMISSION);
                
                Log::info('订单奖励发放成功', [
                    'order_id' => $order->id,
                    'user_id' => $user->id,
                    'reward_amount' => $rewardAmount,
                    'reward_coins' => $rewardCoins,
                    'exchange_rate' => $exchangeRate
                ]);
            }

            DB::commit();

            return response()->json([
                'status' => 1,
                'message' => '接收成功'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            
            Log::error('订单处理失败', [
                'request_data' => $request->all(),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'status' => 0,
                'message' => '处理失败'
            ]);
        }
    }

    /**
     * 查询订单状态
     */
    public function status(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'request_id' => 'required|integer',
            'media_id' => 'required|integer',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 0,
                'message' => '参数错误'
            ]);
        }

        $order = ThirdPartyOrder::where('request_id', $request->request_id)
            ->where('media_id', $request->media_id)
            ->first();

        if (!$order) {
            return response()->json([
                'status' => 0,
                'message' => '订单不存在'
            ]);
        }

        return response()->json([
            'status' => 1,
            'message' => '查询成功',
            'data' => [
                'order_status' => $order->status,
                'processed_at' => $order->processed_at ? $order->processed_at->format('Y-m-d H:i:s') : null,
                'reward_coins' => $order->reward_coins
            ]
        ]);
    }

    /**
     * 验证签名
     */
    private function validateSignature(Request $request): bool
    {
        // 获取媒体配置中的app_key (这里需要根据media_id获取对应的app_key)
        $appKey = $this->getAppKeyByMediaId($request->media_id);
        
        Log::info('签名验证调试', [
            'media_id' => $request->media_id,
            'app_key' => $appKey,
            'app_key_length' => strlen($appKey)
        ]);
        
        if (empty($appKey)) {
            Log::warning('签名验证失败：未找到媒体对应的app_key', [
                'media_id' => $request->media_id
            ]);
            return false;
        }

        // 按照文档要求生成签名字符串
        $signContent = 'request_id' . $request->request_id .
            'media_id' . $request->media_id .
            'user_id' . $request->user_id .
            'media_userid' . $request->media_userid .
            'type' . $request->type .
            'data_id' . $request->data_id .
            'task_id' . $request->task_id .
            'reward' . $request->reward .
            'media_price' . $request->media_price .
            'reward_time' . $request->reward_time .
            'remark' . $request->remark .
            $appKey;
            
        // 调试信息
        Log::info('签名计算详情', [
            'content' => $signContent,
            'content_length' => strlen($signContent),
            'content_bytes' => bin2hex($signContent),
            'remark_bytes' => bin2hex($request->remark),
            'remark_raw' => $request->remark,
            'request_encoding' => mb_detect_encoding($request->remark),
            'request_headers' => $request->headers->all(),
            'php_version' => PHP_VERSION,
            'encoding' => mb_detect_encoding($signContent),
        ]);
        
        $signString = md5($signContent);

        $isValid = $signString === $request->sign;
        
        if (!$isValid) {
            // 生成签名字符串用于调试
            $debugSignContent = 'request_id' . $request->request_id .
                'media_id' . $request->media_id .
                'user_id' . $request->user_id .
                'media_userid' . $request->media_userid .
                'type' . $request->type .
                'data_id' . $request->data_id .
                'task_id' . $request->task_id .
                'reward' . $request->reward .
                'media_price' . $request->media_price .
                'reward_time' . $request->reward_time .
                'remark' . $request->remark .
                $appKey;
                
            Log::warning('签名验证失败', [
                'media_id' => $request->media_id,
                'expected_sign' => $signString,
                'received_sign' => $request->sign,
                'sign_content' => $debugSignContent,
                'app_key' => $appKey,
                'params_debug' => [
                    'request_id' => $request->request_id . ' (' . gettype($request->request_id) . ')',
                    'media_id' => $request->media_id . ' (' . gettype($request->media_id) . ')',
                    'user_id' => $request->user_id . ' (' . gettype($request->user_id) . ')',
                    'media_userid' => $request->media_userid . ' (' . gettype($request->media_userid) . ')',
                    'type' => $request->type . ' (' . gettype($request->type) . ')',
                    'data_id' => $request->data_id . ' (' . gettype($request->data_id) . ')',
                    'task_id' => $request->task_id . ' (' . gettype($request->task_id) . ')',
                    'reward' => $request->reward . ' (' . gettype($request->reward) . ')',
                    'media_price' => $request->media_price . ' (' . gettype($request->media_price) . ')',
                    'reward_time' => $request->reward_time . ' (' . gettype($request->reward_time) . ')',
                    'remark' => $request->remark . ' (' . gettype($request->remark) . ')',
                ]
            ]);
        }

        return $isValid;
    }

    /**
     * 根据媒体ID获取对应的app_key
     * 这里需要根据你的实际业务逻辑来实现
     */
    private function getAppKeyByMediaId(int $mediaId): string
    {
        // 方案1: 从数据库媒体表中获取
        // $media = Media::find($mediaId);
        // return $media ? $media->app_key : '';

        // 媒体配置 (根据你提供的媒体信息)
        $mediaConfigs = [
            143554 => '3a7842025b8fe34511afdb7235a70c01', // 来头游戏库
            // 可以添加更多媒体配置
        ];

        return $mediaConfigs[$mediaId] ?? '';
    }

    /**
     * 验证请求格式和编码
     */
    private function validateRequestFormat(Request $request): void
    {
        // 检查Content-Type头
        $contentType = $request->header('Content-Type', '');
        $hasUtf8 = stripos($contentType, 'utf-8') !== false;
        
        // 检查关键字段的编码
        $remark = $request->input('remark', '');
        $remarkEncoding = mb_detect_encoding($remark, ['UTF-8', 'GBK', 'GB2312', 'ASCII'], true);
        $isValidUtf8 = mb_check_encoding($remark, 'UTF-8');
        
        // 检查请求格式
        $isJson = stripos($contentType, 'application/json') !== false;
        $isForm = stripos($contentType, 'application/x-www-form-urlencoded') !== false;
        
        // 记录请求格式和编码检查结果
        Log::info('请求格式和编码验证', [
            'content_type' => $contentType,
            'is_json' => $isJson,
            'is_form' => $isForm,
            'has_utf8_header' => $hasUtf8,
            'remark' => $remark,
            'remark_encoding' => $remarkEncoding,
            'is_valid_utf8' => $isValidUtf8,
            'remark_bytes' => bin2hex($remark),
            'request_method' => $request->method(),
            'user_agent' => $request->header('User-Agent'),
            'raw_input' => $request->getContent(),
            'all_params' => $request->all(),
            'all_headers' => $request->headers->all()
        ]);
        
        // 如果包含中文但不是有效的UTF-8，记录警告
        if (!empty($remark) && preg_match('/[\x{4e00}-\x{9fff}]/u', $remark) && !$isValidUtf8) {
            Log::warning('检测到非UTF-8编码的中文字符', [
                'remark' => $remark,
                'detected_encoding' => $remarkEncoding,
                'content_type' => $contentType
            ]);
        }
        
        // 如果Content-Type没有指定UTF-8，记录提醒
        if (!$hasUtf8) {
            Log::info('建议在Content-Type中指定UTF-8编码', [
                'current_content_type' => $contentType,
                'recommended' => 'application/json; charset=utf-8'
            ]);
        }
    }
}
